<template>
  <div class="right-search-box">
    <div class="key-person">
      <div class="key-person-label">关键人：</div>
      <je-input
        v-model:value="pageData.userName"
        placeholder="搜索"
        autocomplete="false"
        class="left-search-box"
      >
        <template #prefix>
          <i class="fal fa-search" style="padding-right: 2px"></i>
        </template>
      </je-input>
    </div>
    <div class="key-date">
      <div class="key-date-label">送交日期：</div>
      <je-range-picker
        v-model:value="rangeDate"
        ge-picker
        :locale="locale"
        :placeholder="['开始日期', '结束日期']"
        :get-popup-container="popupContainer"
        @change="changeRangeDate"
      />
    </div>
  </div>
  <div class="right-content-box">
    <div v-show="flowList.length > 0 && !loading" class="right-content-main-box">
      <div v-for="flowItem in flowList" :key="flowItem.id" class="right-content-item">
        <div v-if="flowItem.submitUserPhoto" class="recore-avatar"
          ><img :src="formatAvatar(flowItem.submitUserPhoto)" alt="" />
          <div
            v-show="pageData.type == 'PI_INFORMIEREN'"
            class="right-content-status"
            :style="{ background: flowItem.isReadCode == '0' ? '#ff625c' : '#a9aba9' }"
          ></div>
        </div>
        <div v-if="!flowItem.submitUserPhoto" class="right-content-name">
          <span v-text="formatName(flowItem.submitUserName)"></span>
          <div
            v-show="pageData.type == 'PI_INFORMIEREN'"
            class="right-content-status"
            :style="{ background: flowItem.isReadCode == '0' ? '#ff625c' : '#a9aba9' }"
          ></div>
        </div>

        <div class="right-content-main">
          <div class="right-content-main-top">
            <div
              class="rigth-main-top-describe"
              @click="
                handldShowForm(
                  flowItem.funcCode,
                  flowItem.pkValue,
                  flowItem.isReadCode,
                  flowItem.id,
                )
              "
              v-html="flowItem.title"
            ></div>
            <div class="rigth-main-top-handle">
              <je-tooltip placement="bottom">
                <template #title>
                  <span>{{ flowItem.delay == 1 ? '取消延时' : '延时处理' }}</span>
                </template>
                <i
                  v-if="showDelays.includes(pageData.type)"
                  class="fas fa-clock"
                  :class="{ 'handle-mark': flowItem.delay == 1 }"
                  @click="handleDelay(flowItem.id, flowItem.delay)"
                ></i>
              </je-tooltip>
              <je-tooltip placement="bottom">
                <template #title>
                  <span>{{ flowItem.collect == 1 ? '取消标记' : '加入标记' }}</span>
                </template>
                <i
                  v-if="!noShowCollects.includes(pageData.type)"
                  class="fas fa-star"
                  :class="{ 'handle-mark': flowItem.collect == 1 }"
                  @click="handleMark(flowItem.piid, flowItem.collect)"
                ></i>
              </je-tooltip>
            </div>
          </div>
          <div class="right-content-main-bottom" v-html="flowItem.context"> </div>
        </div>
      </div>
    </div>
    <div v-show="flowList.length > 0 && !loading" class="page-box">
      <je-pagebar
        :page-size="pageData.limit"
        :total-count="pageData.totalCount"
        @load="getFlowData"
      ></je-pagebar>
    </div>
    <div v-loading="loading"></div>
    <div v-show="flowList.length == 0 && !loading" class="no-data-box">
      <img :src="noData" alt="" />
      <div class="no-data-explain">暂无数据～</div>
    </div>
  </div>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, ref, watch, onBeforeUnmount } from 'vue';
  import { Modal, DatePicker, Input } from '@jecloud/ui';
  import locale from 'ant-design-vue/lib/date-picker/locale/zh_CN';
  import { useMicroStore } from '@common/store/micro-store';
  import { Tooltip } from 'ant-design-vue';
  import JePagebar from '@/components/page-bar.vue';
  import noData from '@/assets/no-data.png';
  import { dateFormat, getFileUrlByKey } from '@jecloud/utils';
  import { showFuncForm } from '@jecloud/func';
  import { moveLocation } from '@/helper/publish';
  import { GetTask, AddCollect, DelayManage, updateExamineRead } from '@/api';
  export default defineComponent({
    name: 'FlowCheckItem',
    components: {
      JeRangePicker: DatePicker.RangePicker,
      JeTooltip: Tooltip,
      JeInput: Input,
      JePagebar,
    },
    props: {
      checkType: {
        type: String,
        default: () => '',
      },
      endStatus: {
        type: String,
        default: () => '0',
      },
      sortCode: {
        type: String,
        default: () => '',
      },
    },
    emits: ['flowChildCount'],
    setup(props, { emit, expose }) {
      const microStore = useMicroStore();
      let loading = ref(false); //请求数据loading
      let searchTimeout = null; //关键人搜索
      const validatorType = ['PI_APPROVED', 'PI_OWNER'];
      const state = reactive({
        noData, //缺省图
        rangeDate: null, //自定义时间
        locale,
        showDelays: ['PI_PREAPPROV', 'PI_DELAY'], //可以显示延迟操作的子应用
        noShowCollects: ['PI_INFORMIEREN'], //不显示加入标记的流程子应用
        flowList: [], //流程列表
        pageData: {
          type: props.checkType, //查询类型
          userName: '', //关键人
          startTime: '', //开始时间
          endTime: '', //结束时间
          end: props.endStatus, //是否完结 1已完结，0未完结
          page: 1, //页码
          limit: 30, //限制条数
          totalCount: 0, //总条数
          sort: props.sortCode, //流程分类
        },
        handleFlag: true, //状态操作标识
      });
      const methods = {
        popupContainer(triggerNode) {
          return triggerNode.parentNode;
        },
        changeRangeDate() {
          //日期变化
          if (state.rangeDate) {
            state.pageData.startTime = dateFormat(state.rangeDate[0].toDate(), 'YYYY-MM-DD');
            state.pageData.endTime = dateFormat(state.rangeDate[1].toDate(), 'YYYY-MM-DD');
          } else {
            state.pageData.startTime = '';
            state.pageData.endTime = '';
          }
          methods.getFlowData();
        },
        formatName(name) {
          if (name) {
            return name.slice(name.length - 2);
          }
        },
        formatAvatar(fileKey) {
          //头像转换
          return getFileUrlByKey(fileKey);
        },
        updateCheckNum() {
          //更新流程对应子分类数量
          GetTask(state.pageData).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              emit('flowChildCount', resData.badges);
            }
          });
        },
        handleDelay(id, delayStatus) {
          //延迟处理
          if (state.handleFlag) {
            state.handleFlag = false;
            const param = {
              id: id,
              status: delayStatus == 1 ? '0' : '1',
            };
            DelayManage(param).then((res) => {
              if (res.code == 1000 && res.success) {
                methods.getFlowNoLoadData();
                state.handleFlag = true;
                // methods.updateCheckNum();
                Modal.notice(res.message, 'success');
              }
            });
          }
        },
        handleMark(piid, collectStatus) {
          //加入收藏标记
          if (state.handleFlag) {
            state.handleFlag = false;
            const param = {
              piid: piid,
              status: collectStatus == 1 ? '0' : '1',
            };
            AddCollect(param).then((res) => {
              if (res.code == 1000 && res.success) {
                // state.flowList.forEach((flowItem) => {
                //   if (flowItem.id === id) {
                //     flowItem.collect = collectStatus == 1 ? '0' : '1';
                //     //移动当前元素至首位
                //     // state.flowList = moveLocation(state.flowList, index, 0);
                //     methods.getFlowNoLoadData();
                //   }
                // });
                methods.getFlowNoLoadData();
                state.handleFlag = true;
                Modal.notice(res.message, 'success');
              }
            });
          }
        },
        getFlowNoLoadData() {
          //没有loading效果的获取数据
          GetTask(state.pageData).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.flowList = resData.data.rows;
              state.pageData.totalCount = resData.data.totalCount;
              if (state.pageData.userName) {
                state.flowList.forEach((flowItem) => {
                  //标题高亮
                  flowItem.title = flowItem.title.replaceAll(
                    state.pageData.userName,
                    `<span class="hight-str">${state.pageData.userName}</span>`,
                  );
                  //流程内容
                  flowItem.context = flowItem.context.replaceAll(
                    state.pageData.userName,
                    `<span class="hight-str">${state.pageData.userName}</span>`,
                  );
                });
              }
              emit('flowChildCount', resData.badges);
            }
          });
        },
        getFlowData(pageInfo) {
          //获取对应流程列表
          if (pageInfo) {
            state.pageData.page = pageInfo.page;
          }
          loading.value = true;
          GetTask(state.pageData).then((res) => {
            if (res.code == 1000 && res.success) {
              const resData = res.data;
              state.flowList = resData.data.rows;
              state.pageData.totalCount = resData.data.totalCount;
              if (state.pageData.userName) {
                state.flowList.forEach((flowItem) => {
                  //标题高亮
                  flowItem.title = flowItem.title.replaceAll(
                    state.pageData.userName,
                    `<span class="hight-str">${state.pageData.userName}</span>`,
                  );
                  //流程内容
                  flowItem.context = flowItem.context.replaceAll(
                    state.pageData.userName,
                    `<span class="hight-str">${state.pageData.userName}</span>`,
                  );
                });
              }
              emit('flowChildCount', resData.badges);
              setTimeout(() => {
                loading.value = false;
              }, 100);
            }
          });
        },
        handldShowForm(funcCode, funcId, isReadCode, itemId) {
          //展示功能表单
          showFuncForm(funcCode, {
            beanId: funcId,
          });
          //审批公告更改已读状态
          if (props.checkType == 'PI_INFORMIEREN' && isReadCode == 0) {
            updateExamineRead({ pkId: itemId }).then((res) => {
              if (res.success) {
                methods.getFlowData();
              }
            });
          }
        },
        watchFlowCheckType(typeStr) {
          //监听流程审核分类变化
          state.pageData.sort = typeStr;
          state.pageData.page = 1;
          methods.getFlowData();
        },
        socketMessage(message) {
          //websocket通知-流程
          if (message.busType == 'WF') {
            //推送通知类型与当前选中类型相同时，需要刷新当前列表数据
            methods.getFlowNoLoadData();
          }
        },
      };
      watch(
        () => state.pageData.userName,
        (newVal, oldVal) => {
          if (newVal !== oldVal) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
              state.pageData.page = 1;
              methods.getFlowData();
            }, 1000);
          }
        },
      );
      watch(
        //监听已完结/未完结状态变化
        () => props.endStatus,
        (newVal, oldVal) => {
          if (newVal != oldVal && validatorType.includes(props.checkType)) {
            state.pageData.end = newVal;
            state.pageData.page = 1;
            methods.getFlowData();
          }
        },
      );
      watch(
        //监听流程分类变化
        () => props.sortCode,
        (newVal, oldVal) => {
          if (newVal !== oldVal) {
            state.pageData.sort = newVal;
            state.pageData.page = 1;
            methods.getFlowData();
          }
        },
      );
      //注册websocket监听事件
      microStore.on('websocket-message', (message) => {
        methods.socketMessage(message);
      });
      onMounted(() => {
        methods.getFlowData();
      });
      onBeforeUnmount(() => {});
      return {
        loading,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style>
  .right-content-main-bottom .flow-remark {
    color: #ff625c;
  }
</style>
<style scoped lang="less">
  .right-search-box {
    width: 100%;
    height: 40px;
    padding: 0 20px;
    box-sizing: border-box;
    border-top: 1px solid #ecedf0;
    border-right: 1px solid #ecedf0;
    border-bottom: 1px solid #ecedf0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .key-person {
      display: flex;
      align-items: center;
      .key-person-label {
        font-size: 14px;
        color: #3f3f3f;
      }
      .ant-input-affix-wrapper {
        width: 160px;
        border: 1px solid #f5f5f5;
        box-sizing: border-box;
      }
    }
    .key-date {
      display: flex;
      align-items: center;
      .key-date-label {
        font-size: 14px;
        color: #3f3f3f;
      }
      .ant-picker {
        width: 322px;
        border: 1px solid #f5f5f5;
        box-sizing: border-box;
      }
    }
  }
  .right-content-box {
    width: 100%;
    height: 500px;
    box-sizing: border-box;
    border-right: 1px solid #ecedf0;
    border-bottom: 1px solid #ecedf0;
    background-color: #ffffff;
    position: relative;
    .right-content-main-box {
      width: 100%;
      height: 460px;
      overflow-y: auto;
    }
    .right-content-item {
      width: calc(100% - 40px);
      height: 70px;
      box-sizing: border-box;
      padding: 14px 0;
      display: flex;
      align-items: center;
      margin: 0 20px;
      background-color: #ffffff;
      border-bottom: 1px solid #ecedf0;
      overflow: hidden;
      .right-content-name {
        width: 34px;
        height: 34px;
        line-height: 34px;
        border-radius: 50%;
        background-color: #faa03a;
        font-size: 12px;
        color: #ffffff;
        text-align: center;
        margin-right: 20px;
        flex-shrink: 0;
        position: relative;
        .right-content-status {
          width: 6px;
          height: 6px;
          border-radius: 50%;
          position: absolute;
          left: 46px;
          top: 0px;
        }
      }
      .right-content-main {
        width: calc(100% - 54px);
        flex-shrink: 0;
        overflow: hidden;

        .right-content-main-top {
          width: 100%;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .rigth-main-top-describe {
            height: 20px;
            line-height: 20px;
            font-size: 14px;
            color: #333333;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .rigth-main-top-handle {
            i {
              cursor: pointer;
              font-size: 14px;
              color: #a9aba9;
              margin-left: 10px;
            }
            .handle-mark {
              color: #faa03a;
            }
          }
        }
        .right-content-main-bottom {
          width: 574px;
          font-size: 12px;
          color: #a9aba9;
          margin-top: 8px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
      .recore-avatar {
        width: 34px;
        height: 34px;
        text-align: center;
        border-radius: 100%;
        margin-right: 20px;
        position: relative;
        img {
          width: 34px;
          height: 34px;
          border-radius: 100%;
        }
        .right-content-status {
          width: 6px;
          height: 6px;
          border-radius: 50%;
          position: absolute;
          left: 46px;
          top: 0px;
        }
      }
    }
    .right-content-item:last-child {
      border-bottom: none;
    }
    .right-content-item:hover .right-content-main .rigth-main-top-describe {
      color: @primary-color;
      cursor: pointer;
    }
  }
  .right-content-main-box::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
  .page-box {
    width: 100%;
    height: 40px;
    padding: 7px 20px 0;
  }
  .no-data-box {
    width: 100%;
    padding-top: 140px;
    img {
      display: block;
      width: 319px;
      height: 194px;
      margin: 0 auto;
    }
    .no-data-explain {
      width: 100%;
      text-align: center;
      font-size: 14px;
      color: #a9aba9;
      padding-top: 20px;
    }
  }
</style>
